#/bin/bash
set -Eeo pipefail
declare GS_PORT=${GS_PORT:-46432}
declare GS_USERNAME=${GS_USERNAME:-hbu}

declare max_retry_primary_num=${max_retry_primary_num:-2}
declare max_retry_primary_interval=${max_retry_primary_interval:-5}

export GS_PASSWORD='Gauss!23'
export PRIMARYHOST=172.16.85.131
#export STANDBYHOSTS="172.11.0.3, 172.11.0.4"
export STANDBYHOSTS="172.16.85.131"
# Execute sql script, passed via stdin (or -f flag of pqsl)
# usage: docker_process_sql [gsql-cli-args]
#    ie: docker_process_sql --dbname=mydb <<<'INSERT ...'
#    ie: docker_process_sql -f my-file.sql
#    ie: docker_process_sql <my-file.sql
function docker_process_sql() {
    local query_runner=( gsql -v ON_ERROR_STOP=1 --username "$GS_USER" --password "$GS_PASSWORD")
    if [ -n "$GS_DB" ]; then
        query_runner+=( --dbname "$GS_DB" )
    fi
    if [ -n "$GS_PORT" ]; then
        query_runner+=( --port "$GS_PORT" )
    fi

    echo "Execute SQL: ${query_runner[@]} $@"
    "${query_runner[@]}" "$@"
}

function opengauss_setup_cluster_conf() {
    echo "setup GS_PORT=${GS_PORT}"
    correct_network_ip=$(ip route show |grep -v default | grep $(ip route show | grep default | awk '{print $5}') | awk '{print $9}')
    
    host_array=(${PRIMARYHOST})
    standby_hosts=${STANDBYHOSTS}
    #standby_hosts=(${standby_hosts//\"/})
    host_array+=(${standby_hosts//[,\"]/ })
    # It needs to enhance capture $correct_network_ip logic, if the host has 2 network interfaces.
    echo "Cluster nodes: ${host_array[@]}"
    echo "Stanby nodes: ${standby_hosts[@]}"
    index=1
    for ((i = 0; i < ${#host_array[@]}; i++)); do
        if [ "${correct_network_ip}" != "${host_array[i]}" ]; then
            echo "replconninfo${index}='localhost=${correct_network_ip} localport=5433 localheartbeatport=5436 remotehost=${host_array[i]} remoteport=5433 remoteheartbeatport=5436'"
            #gs_guc set -D ${datanode_dir} -c "replconninfo${index}='localhost=${correct_network_ip} localport=5433 localheartbeatport=5436 remotehost=${host_array[i]} remoteport=5433 remoteheartbeatport=5436'"
            index=$(expr $index + 1)
        fi
        #gs_guc set -D ${datanode_dir} -h "host all all ${host_array[i]}/32 trust"
    done
    echo "$index, ${#host_array[@]}"
    if [ $index == 2 ]; then
        echo "Master-slave cluster with 2 openGauss instances, set sync_most_available=on." 
        #gs_guc set -D ${datanode_dir} -c "sync_most_available=on"
    fi
}


function docker_check_primary() {
    #local query_runner=(gsql -d "host=$PRIMARYHOST port=${GS_PORT} dbname=postgres")
    if [ -z "$GS_PORT" ]; then
        GS_PORT=5432
    fi
    echo
    echo "Start to check openGauss primary instance status at host:  ${PRIMARYHOST}..."
    is_primary_running=0
    set +e 
    for ((i=1;i<=max_retry_primary_num;i++)); do
        echo "Check openGauss primary instance status with loop number=$i"
        #QUERY_PRIMARY_REUSLT=$(gsql -v ON_ERROR_STOP=0 -d "host=$PRIMARYHOST port=${GS_PORT} dbname=postgres user=$GS_USERNAME password=${GS_PASSWORD}" -c "SELECT name, setting FROM pg_settings where name like 'replconninfo%';")
        gsql -v ON_ERROR_STOP=0 -d "host=$PRIMARYHOST port=${GS_PORT} dbname=postgres user=$GS_USERNAME password=${GS_PASSWORD}" -c "SELECT name, setting FROM pg_settings where name like 'replconninfo%';" $?
        if [ -z "$QUERY_PRIMARY_REUSLT" ];then
            echo 
            echo "There is no replconninfo* settings found."
            echo 
            sleep ${max_retry_primary_interval}
        else
            echo "$QUERY_PRIMARY_REUSLT" 
            #if [ $(echo "$QUERY_PRIMARY_REUSLT" |grep 172.11.0.2 | grep replconninfo | wc -l) -gt 0 ]; then
            if [ $(echo "$QUERY_PRIMARY_REUSLT" |grep 172.11.0.2 | wc -l) -gt 0 ]; then
                is_primary_running=$(expr $is_primary_running + 1)
            fi 
            echo "is_primary_running=$is_primary_running"
            # introduce double check mechanism
            if [ $is_primary_running -gt 1 ];then
                echo "Double check openGauss primary instance status, and it is running at host: ${PRIMARYHOST}..."
                is_primary_running=0
                break
            else
                sleep ${max_retry_primary_interval} 
            fi
        fi
    done 
    echo
    set -e
    return 1
}
max_retry_num=10
max_retry_interval=10
for ((i=1;i<=max_retry_num;i++)); do
  echo "Number $i"
  if [ $i -ge 5 ];then
      break
  fi
done
echo "GS_PORT=${GS_PORT}"
if [ -n "$STANDBYHOSTS" ]; then
    #opengauss_setup_cluster_conf
    docker_check_primary
    echo "return $?"
fi

echo "Last check set -e"
gsql -v ON_ERROR_STOP=0 -d "host=$PRIMARYHOST port=${GS_PORT} dbname=postgres user=$GS_USERNAME password=${GS_PASSWORD}" -c "SELECT name, setting FROM pg_settings where name like 'replconninfo%';" $?
echo "End set -e"